package com.alibaba.serverless.service.impl;

import com.alibaba.serverless.common.constant.SmtpServiceConstants;
import com.alibaba.serverless.common.domain.AliYunSmtpConfig;
import com.alibaba.serverless.common.exception.BizException;
import com.alibaba.serverless.common.util.RedisUtils;
import com.alibaba.serverless.domain.ReceiveParams;
import com.alibaba.serverless.service.SmtpService;
import com.alibaba.serverless.service.handle.SmtpContent;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.BatchSendMailRequest;
import com.aliyuncs.dm.model.v20151123.BatchSendMailResponse;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 朱永杰
 */
@SuppressWarnings("all")
public class ISmtpServiceImpl extends AliYunSmtpConfig implements SmtpService {
    private final Logger logger = LoggerFactory.getLogger(ISmtpServiceImpl.class);
    private final RedisUtils redisService=new RedisUtils();
    protected static final Integer  ONE_DAY = 60 * 60 * 24;
    protected static final Integer ONE_MINE = 60;
    protected static final Integer ONE_HOUR = 60 * 60;
    public ISmtpServiceImpl() {
        super();
    }

    private IAcsClient client;

    @Override
    public void demo() {
        IAcsClient client =getClient();
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            request.setVersion("2015-11-23");
            request.setAccountName("register@send.xianyun.site");
            request.setFromAlias("闲云");
            request.setAddressType(0);
            request.setReplyToAddress(false);
            request.setTagName("VerificationCode");
            request.setToAddress("1436550119@qq.com");
            //可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
            //request.setToAddress("邮箱1,邮箱2");
            request.setSubject("闲云");
            String httpBody ="尊敬的 {UserName}{Gender}您好，欢迎注册闲云博客系统。请将验证码填写到注册页面。验证码：{VerificationCode}";
            request.setHtmlBody(httpBody);
            SingleSendMailResponse httpResponse = client.getAcsResponse(request);
            logger.info("EnvId:{},RequestId:{}",  httpResponse.getEnvId(),httpResponse.getRequestId());
        } catch (ClientException e) {
            logger.error("Smtp ClientException:{}", e.getErrMsg());
            throw new BizException("客户端设置异常");
        }
    }

    @Override
    public void batchSendMailDemo() {
        IAcsClient client = getClient();
        BatchSendMailRequest request = new BatchSendMailRequest();
        try {
            request.setVersion("2015-11-23");
            request.setAccountName("register@send.xianyun.site");
            request.setAddressType(0);
            request.setTagName("VerificationCode");
            request.setTemplateName("注册");
            request.setReceiversName("subscribe");
            BatchSendMailResponse httpResponse = client.getAcsResponse(request);
            logger.info("EnvId:{},RequestId:{}",  httpResponse.getEnvId(),httpResponse.getRequestId());
        } catch (ClientException e) {
            logger.error("Smtp ClientException:{}", e.getErrMsg());
            throw new BizException("客户端设置异常");
        }
    }

    @Override
    public void sendSingleApiMail(ReceiveParams smtpParams) {
        IAcsClient client =getClient();
        SmtpContent smtpContent = new SmtpContent(smtpParams.getType());
        SingleSendMailRequest request=smtpContent.sendSingleMailRequest(smtpParams);
        try {
            synchronized (client){
                String toAddress=smtpParams.getToAddress();
                client.getAcsResponse(request);
                if (smtpParams.getType()==1){
                    String repeatCheckKey=toAddress+ SmtpServiceConstants.REPEAT_CHECK;
                    setRedisCheck(repeatCheckKey,smtpParams.getCheckCode(),toAddress);
                }
                logger.info(smtpParams.getConditionName()+"---"+"emailSend:"+toAddress+"---邮件已发送");
            }
        }catch (ClientException  e) {
            logger.warn("Smtp ClientException:{}", e.getErrMsg());
            e.printStackTrace();
            throw new BizException("客户端设置异常");
        }
    }

    @Override
    public void sendBatchApiMail(ReceiveParams smtpParams) {

    }

    private void setRedisCheck(String repeatCheckKey,String code,String email){
        try {
            /**设置短信发送间隔时间*/
            redisService.setEx(repeatCheckKey,SmtpServiceConstants.SMTP_REDIS_EXPIRATION * ONE_MINE, code);
            String timesCheckKey=email+ SmtpServiceConstants.TIMES_CHECK;
            String redisGetTimes=redisService.get(timesCheckKey);
            Integer sendTimesInLastHour= 0;
            if(null!=redisGetTimes){
                sendTimesInLastHour=Integer.parseInt(redisGetTimes);
            }
            /**设置当前短信发送次数间隔时间*/
            redisService.setEx(timesCheckKey, SmtpServiceConstants.CHECK_SMTP_SEND_TIMES_TIME * ONE_HOUR,++sendTimesInLastHour+"");
            /**设置短信存活时间*/
            redisService.setEx(email, SmtpServiceConstants.SMTP_USE_EXPIRATION * ONE_MINE,code);
        } catch (Exception e)
        {
            logger.warn("BizException with error ,error message:{}",e.getMessage());
        }
    }



    private IAcsClient getClient(){
        while (null == client){
            setIAcsClient();
        }
        return client;
    }

    private synchronized void setIAcsClient(){
        // 如果是除杭州region外的其它region（如新加坡、澳洲Region），需要将下面的”cn-hangzhou”替换为”ap-southeast-1”、或”ap-southeast-2”。
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKey, secretKey);
        client = new DefaultAcsClient(profile);
    }

}
